package 力扣日常刷题.木23一月.第16天316;

import 力扣日常刷题.TreeNode;

import java.util.*;

/**
 * @author 帅小伙
 * @date 2022/3/16
 * @description
 */
public class Demo83二叉树的锯齿形层序遍历 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root == null) return ans;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);
        int t = 0;
        while(!deque.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = deque.size() - 1; i >= 0; i--) {
                TreeNode pop = deque.pollFirst();
                list.add(pop.val);
                if(pop.left!= null) deque.addLast(pop.left);
                if(pop.right!= null) deque.addLast(pop.right);
            }
            if(t % 2 == 1) {
                Collections.reverse(list);
            }
            ans.add(list);
        }
        return ans;
    }

}
